from django.shortcuts import render

# Create your views here.
from rest_framework import status
from rest_framework.views import APIView
from .models import Area
from .serializers import AreaSerializer, SubAreaSerializer
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

# """第一种实现方式"""
# class AreaListView(APIView):
#     """查询所有"""
#
#     def get(self, request):
#         #1.获取所有的查询集
#         # qs = Area.objects.filter(parent=None)
#         qs = Area.objects.filter(parent=None)
#         #2.创建序列化器进行序列化
#         serializer = AreaSerializer(qs, many=True)
#         #3.响应
#         return Response(serializer.data)
#
# class AreaDetailView(APIView):
#     """查询单一省市区"""
#
#     def get(self, request, pk):
#         #1.根据pk查询出指定的省或市
#         try:
#             area = Area.objects.get(id = pk)
#         except Area.DoesNotExist:
#             return Response({'message': '无效pk'}, status=status.HTTP_400_BAD_REQUEST)
#         #2.创建序列化器进行序列化
#         serializer = SubAreaSerializer(area)
#         #3.响应
#         return Response(serializer.data)

"""第二种实现方式"""
class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """
    行政区划信息
    """
    pagination_class = None  # 区划信息不分页

    def get_queryset(self):
        """
        指定查询集
        """
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        """
        指定序列化器
        """
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer